import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:logger/logger.dart';

class HttpTestRoute extends StatefulWidget {
  const HttpTestRoute({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _HttpTestRouteState();
}

class _HttpTestRouteState extends State<HttpTestRoute> {
  final logger = Logger(printer: LogfmtPrinter());

  bool _loading = false;

  String _text = "";

  _request() async {
    setState(() {
      _loading = true;
      _text = "正在请求中...";
    });
    try {
      var httpClient = HttpClient();
      var request = await httpClient.getUrl(Uri.parse("https://www.baidu.com"));

      //使用iPhone的UA
      request.headers.add(
        "user-agent",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",
      );

      //等待连接服务器（会将请求信息发送给服务器）
      var response = await request.close();
      _text = await response.transform(utf8.decoder).join();

      //输出响应头
      logger.i(response.headers);

      httpClient.close();
    } catch (e) {
      _text = "请求失败：$e";
    } finally {
      setState(() {
        _loading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Http Client Test'),
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Column(
            children: [
              ElevatedButton(
                child: const Text("获取百度首页"),
                onPressed: _loading ? null : _request,
              ),
              SizedBox(
                child: SelectableText(_text.replaceAll(RegExp(r"\s"), "")),
              )
            ],
          ),
        ),
      ),
    );
  }
}
